﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.DomainModel;

namespace MethodWorx.CMS.Workflow
{
    [Serializable]
    public class WorkflowConfiguration
    {
        public string Name { get; set; }
        public string InvokeOnHttpMethod { get; set; }
        public string InvokeOnPageEvent { get; set; }
        public WorkflowConfigurationStep StartingStep { get; set; }
        public bool Shared { get; set; }

        public WorkflowConfigurationStep FindStep(Guid stepId)
        {
            return this.FindStepRecursive(this.StartingStep, stepId);
        }

        private WorkflowConfigurationStep FindStepRecursive(WorkflowConfigurationStep step, Guid stepId)
        {
            if(step != null && step.Id == stepId)
                return step;
            else
            {
                if(step.Steps != null)
                {
                    foreach(var childStep in step.Steps)
                    {
                        var foundStep = FindStepRecursive(childStep, stepId);
                        if (foundStep != null)
                            return foundStep;
                    }
                }
            }

            return null;
        }

        public void DeleteStep(Guid stepId)
        {
            this.DeleteStepRecursive(null, this.StartingStep, stepId);
        }

        private bool DeleteStepRecursive(WorkflowConfigurationStep parent, WorkflowConfigurationStep step, Guid stepId)
        {
            if(step.Id == stepId)
            {
                if (parent == null)
                    this.StartingStep = null;
                else
                {
                    parent.Steps = parent.Steps.Where(s => s.Id != stepId).ToArray();
                }
                return true;
            }
            else
            {
                foreach(var child in step.Steps)
                {
                    var res = DeleteStepRecursive(step, child, stepId);
                    if (res)
                        return res;
                }
            }
            return false;
        }
    }
}
